const md5 = require('md5-node')

// 用于捕获async/await返回的错误
function asyncRes(promise) {
  return promise.then(res => [null, res]).catch(err => [err, null])
}
// 产生随机数
function randNum(maxNum, minNum) {
  if (arguments.length === 0) {
    return Math.random()
  } else if (arguments.length === 1) {
    return parseInt(Math.random() * (maxNum + 1))
  } else {
    return parseInt(Math.random() * (maxNum - minNum + 1) + minNum)
  }
}

// 产生注册唯一标识
function makeEkey(email) {
  // 混肴email
  let str = email
  for (let i = 0; i < email.length; i++) {
    const index = email.charCodeAt(i) % email.length
    str = splice(str, index, email[i])
  }
  // md5(md5(fspaceleazer)) 28106164575df2a03321db0cc1476903
  // md5(md5(thebestwebsite)) 872ea82dd5452136370dc0822d9b1d98
  return md5(md5(str + '28106164575df2a03321db0cc1476903').slice(0, 16) + md5(email + '872ea82dd5452136370dc0822d9b1d98').slice(16)) 
}

// 产生数据的唯一标识
function makeId() {
  const time = Date.now()
  const num = randNum(0, 999999999)
  return md5(time + num)
}

// 返回邮件验证码
function getAuthCode() {
  let str = ''
  for (let i = 0; i < 6; i++) {
    str += randNum(0, 9)
  }
  return str
}

// 密码加密
function encryptPassword(password) {
  // 混肴password
  let str = password
  for (let i = 0; i < password.length; i++) {
    const index = password.charCodeAt(i) % password.length
    str = splice(str, index, password[i])
  }
  // md5(md5(20220429mark)) 28106164575df2a03321db0cc1476903
  // md5(md5(leazermakefspace)) 872ea82dd5452136370dc0822d9b1d98
  return md5(md5(str + '853e67673c83a6bb3c7a322c39a8ff71').slice(0, 10) + md5(password + 'a31df95d97f7d5d70d79d914798a7645').slice(10))   
}

// 在字符串中插入值
function splice(str, index, newStr) {
  return str.slice(0, index+1) + newStr + str.slice(index+1)
}

// 生成0-9，a-z，A-Z的数组
function getCaptchaStr () {
  const randArr = []
  for (let i = 0; i <= 9; i++) {
    randArr.push(i.toString())
  }
  for (let i = 65; i < 91; i++) {
    randArr.push(String.fromCharCode(i))
  }
  for (let i = 97; i < 123; i++) {
    randArr.push(String.fromCharCode(i))
  }
  const str = ''
  for (let i = 0; i < 4; i++) {
    str += randArr[randNum(0, randArr.length)]
  }
  return str
}

// 生成不定多字段更新sql语句
function makeUpdateSql(keys, data, table, id, user_id) {
  if (!keys || !data || !id || !user_id || !table){
    return ''
  }
  const sqlParams = []
  let sqlUpdate = `UPDATE ${table} SET`
  for (const x of keys) {
    if (data[x]) {
      if (sqlParams.length !== 0) {
        sqlUpdate += ','
      }
      sqlUpdate += ` ${x}=?`
      sqlParams.push(data[x])
    }
  }
  sqlUpdate += ' WHERE user_id=? AND id=?'
  sqlParams.push(user_id, id)
  return {
    sql: sqlUpdate,
    params: sqlParams
  }
}

// 格式化事件
function formatTime(time) {
  let date = new Date()
  if (time) {
    date = new Date(time)
  }
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  if (hour < 10) {
    hour = '0' + hour
  }
  if (minute < 10) {
    minute = '0' + minute
  }
  if (second < 10) {
    second = '0' + second
  }
  return `${year}/${month}/${day} ${hour}:${minute}:${second}`
}

// 产生roomid
function makeRoomId() {
  let str = ''
  for (let i = 0; i < 6; i++) {
    const num = randNum(0, 9)
    str += num
  }
  return str
}

module.exports = {
  asyncRes: asyncRes,
  randNum: randNum,
  makeEkey: makeEkey,
  getAuthCode: getAuthCode,
  encryptPassword: encryptPassword,
  getCaptchaStr: getCaptchaStr,
  makeId: makeId,
  makeUpdateSql: makeUpdateSql,
  formatTime: formatTime,
  makeRoomId: makeRoomId
}